<?php
/**
 * @author phutp@younetco.com
 */
class Core_Util
{ 
	private static $_locales = array(
		 'AUD' => 'en_AU',
		 'CAD' => 'en_CA',
		 'CZK' => 'cs_CZ',
		 'DKK' => 'da_DK',
		 'EUR' => 'de_DE',
		 'HKD' => 'en_HK',
		 'HUF' => 'hu_HU',
		 'ILS' => 'he_IL',
		 'JPY' => 'ja_JP',
		 'MXN' => 'es_MX',
		 'NOK' => 'nb_NO',
		 'NZD' => 'en_NZ',
		 'PHP' => 'fil_PH',
		 'PLN' => 'pl_PL',
		 'GBP' => 'en_GB',
		 'SGD' => 'en_SG',
		 'SEK' => 'sv_SE',
		 'CHF' => 'fr_CH',
		 'TWD' => 'zh_TW',
		 'THB' => 'th_TH',
		 'USD' => 'en_US',
		 'VND' => 'vi_VN'
	);
	
	public static function formatCurrency($value, $unitCode)
	{
		$locale = self::$_locales[$unitCode];
		$currency = new Zend_Currency($locale);
		$strCurrency = '';
		
		if($unitCode == 'VND' || $unitCode == 'USD')
		{
			$format = array('display' => Zend_Currency::NO_SYMBOL);
			
			if($value - floor($value) == 0)
			{
				// no floating point after value e.g: 5.000 instead of 5.000,00
				$format['precision'] = 0;
			}
			
			$currency->setFormat($format);
			
			if ($unitCode == 'VND')
			{
				$strCurrency = sprintf('%s %s', $currency->setValue($value), $currency->getSymbol());
			}
			else
			{
				$strCurrency = sprintf('%s %s', $currency->getSymbol(), $currency->setValue($value));
			}
		}
		else
		{
			$format = array('display' => Zend_Currency::USE_SYMBOL);
			
			if($value - floor($value) == 0)
			{
				$format['precision'] = 0;
			}
			
			$currency->setFormat($format);
			
			$strCurrency = $currency->setValue($value);
		}
		
		return $strCurrency;
	}
	
	public static function redirect($url) 
	{
		header("Location: $url");
	}
	
	public static function parentRedirect($url) 
	{
		echo "<script language='javascript'>top.location.href='" . $url . "'</script>";
	}
	
	public static function isFacebookRequest()
	{
		$is_fb_request = false;

		if($_SERVER['HTTP_USER_AGENT'] == "facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)")
		{
			$is_fb_request = true;
		}

		return $is_fb_request;
	}
	
	const VIEW_STATE_MANAGE = 'manage_view_state';
	const VIEW_STATE_ENTRY	= 'entry_view_state';
	
	const LATEST_MGS_ID		= 'latest_mgs';
	const THANK_YOU_MSG		= 'thank_you_msg';
	/**
	 *
	 * @param string $mg 
	 */
	public static function setLatestMessage($mg, $key = null)
	{
		$session = Zend_Registry::get('session');
		if(empty($key))
		{
			$session->{self::LATEST_MGS_ID} = $mg;
		}
		else
		{
			$session->{$key} = $mg;
		}
	}

	/**
	 *
	 * @param boolean $clear
	 * @return string 
	 */
	public static function getLatestMessage($key = null, $clear = true)
	{
		$session = Zend_Registry::get('session');
		
		if(empty($key))
		{
			$key = self::LATEST_MGS_ID;
		}
		
		$value	= $session->{$key};

		if( $clear )
		{
			$session->{$key} = NULL;
		}
		
		return $value;
	}
	
	/**
	 * Check is there any message exist in session
	 * @return boolean 
	 */
	public static function hasMessage($key = null)
	{
		$session = Zend_Registry::get('session');
		
		if(empty($key))
		{
			$key = self::LATEST_MGS_ID;
		}
		
		if(!empty($session->{$key}))
		{
			if(trim($session->{$key}) != '')
			{
				return true;
			}
		}
			
		return false;
	}
	
	/**
	 * Remove new line characters, and escape single-quoted
	 * @param string $input
	 * @return string 
	 */
	public static function escapeForJS($input)
	{
        $input  = htmlspecialchars($input);
		$order  = array("\r\n", "\n", "\r");
		$output =  str_replace($order, '', $input);
		$output =  str_replace("'", "\'", $output);
		return $output;
	}	
	/**
	 *
	 * @return Zend_Cache_Frontend_Page
	 */
	public static function getPageCache()
	{
		static $cache = null;
		if( !($cache instanceof Zend_Cache_Frontend_Page) )
		{
			$cache = Zend_Cache::factory(
				'Page',
				'File',
				array(
					'options'		=> array(
						
					)
				),
				array(
					'cache_dir'		=> APPLICATION_PATH.'/../public/cache/file/'
				)
			);
		}
		return $cache;
	}
	
	/**
	 *
	 * @return Zend_Cache_Frontend_Output
	 */
	public static function getOuputCache()
	{
		static $cache = null;
		if( !($cache instanceof Zend_Cache_Frontend_Output) )
		{
			$cache = Zend_Cache::factory(
				'Output',
				'File',
				array(
					'options'		=> array(
						
					)
				),
				array(
					'cache_dir'		=> APPLICATION_PATH.'/../public/cache/file/'
				)
			);
		}
		return $cache;
	}
	
	/**
	 *
	 * @return Zend_Cache_Frontend_Output
	 */
	public static function getFileCache()
	{
		static $cache = null;
		if( !($cache instanceof Zend_Cache_Frontend_Output) )
		{
			$cache = Zend_Cache::factory(
				'Core',
				'File',
				array(
					'automatic_serialization' => true,
				),
				array(
					'cache_dir'		=> APPLICATION_PATH.'/../public/cache/file/'
				)
			);
		}
		return $cache;
	}
	
	public static function createThumbnail($source, $thumbnail, $size)
	{		
		$storage = Zend_Registry::get('storage');
		if ($storage instanceof YouNet_Storage_S3)
		{
			$thumbnail_local = INDEX_PATH . '/../..' . $thumbnail;
			$storage->copyToLocal($source, $thumbnail_local);
			self::cropThumbnail($thumbnail_local,$size); 
			$storage->put($thumbnail, file_get_contents($thumbnail_local)); 
		}
		else
		{
			copy($source, $thumbnail);
			self::cropThumbnail($thumbnail,$size);
		}
	}
	
	public static function createScaledThumbnail($source, $thumbnail, $size)
	{		
		$storage = Zend_Registry::get('storage');
		if ($storage instanceof YouNet_Storage_S3)
		{
			$thumbnail_local = INDEX_PATH . '/../..' . $thumbnail;
			$storage->copyToLocal($source, $thumbnail_local);
			self::cropScaledThumbnail($thumbnail_local, $size);
			$storage->put($thumbnail, file_get_contents($thumbnail_local)); 
		}
		else
		{
			copy($source, $thumbnail);
			self::cropScaledThumbnail($thumbnail, $size);
		}
	}
	
	public static function cropScaledThumbnail($thumbnail, $size)
	{
		list($width, $height) = getimagesize($thumbnail);
		
		$cropHeight = $cropWidth = $size;
		
		if ($width > $height)
		{
			$ratio = $height / $width;
			$cropWidth = $size;
			$cropHeight = round($cropWidth * $ratio);
		}
		else if($width < $height)
		{
			$ratio = $width / $height;
			$cropHeight = $size;
			$cropWidth = round($cropHeight * $ratio);
		}
		else
		{
			$cropWidth = $cropHeight = $size;
		}
		
		Core_ImageUtil::crop($thumbnail, $cropWidth, $cropHeight, 0, 0, $height, $width);
	}	
	
	public static function cropThumbnail($thumbnail,$size)
	{
		list($width, $height) = getimagesize($thumbnail);
		$min = min(array($width, $height));
		
		$cropWidth = $cropHeight = $size;
		Core_ImageUtil::crop($thumbnail, $cropWidth, $cropHeight, 0, 0, $min, $min);
	}
	
		/**
	 * @author hungnq@younetco.com
	 */
	public static function notEmpty($value)
	{
		if ($value !== null && trim($value) !== '' && $value !== array())
		{
			return true;
		}
	}

	/**
	 * Remove null, empty string, empty array
	 * @param array $values
	 * @return array 
	 */
	public static function arrayFilter(array $values)
	{
		$values = array_filter($values, "self::notEmpty");
		return $values;
	}

	public static function removeLink($text)
    {
        $text = preg_replace('/<a.*?>/', '', $text);
        $text = preg_replace('/<\/a>/', '', $text);
        return $text;
    }
	
	public static function standardizePageName($name_page)
	{
		return str_replace(array('"',"'",'?','/','(',')'),array('','','','','',''),$name_page);
	}
	
	public static function getBitlyUrl($long_url)
	{
		$client = new Zend_Http_Client(BITLY_HOST);
		$client->setParameterGet(array(
			'longUrl'	=> $long_url,
			'login'		=> BITLY_USERNAME,
			'apiKey'	=> BITLY_API_KEY
		));
		$response = $client->request();

		$shortUrl = '';
		if( $response->isSuccessful() )
		{
			$response = Zend_Json::decode($response->getBody());
			if($response['status_code'] == 200)
			{
				$shortUrl = $response['data']['url'];
			}
		}
		return $shortUrl;
	}
	public static function translate($key)
	{
		$translator = Zend_Registry::get('Zend_Translate');
		return $translator->translate($key);
	}
	
	 public static function is_ascii($str)
	{
		if (is_array($str))
		{
			$str = implode($str);
		}

		return!preg_match('/[^\x00-\x7F]/S', $str);
	}
	
	public static function substr($str, $offset, $length = NULL)
	{
		if(self::is_ascii($str))
		{
			return ($length === NULL) ? substr($str, $offset) : substr($str, $offset, $length);
		}
		// Normalize params
		$str = (string) $str;
		$strlen = strlen(utf8_decode($str));
		$offset = (int) ($offset < 0) ? max(0, $strlen + $offset) : $offset; // Normalize to positive offset
		$length = ($length === NULL) ? NULL : (int) $length;

		// Impossible
		if ($length === 0 OR $offset >= $strlen OR ($length < 0 AND $length <= $offset - $strlen))
			return '';

		// Whole string
		if ($offset == 0 AND ($length === NULL OR $length >= $strlen))
			return $str;

		// Build regex
		$regex = '^';

		// Create an offset expression
		if ($offset > 0)
		{
			// PCRE repeating quantifiers must be less than 65536, so repeat when necessary
			$x = (int) ($offset / 65535);
			$y = (int) ($offset % 65535);
			$regex .= ($x == 0) ? '' : ('(?:.{65535}){' . $x . '}');
			$regex .= ($y == 0) ? '' : ('.{' . $y . '}');
		}

		// Create a length expression
		if ($length === NULL)
		{
			$regex .= '(.*)'; // No length set, grab it all
		}
		// Find length from the left (positive length)
		elseif ($length > 0)
		{
			// Reduce length so that it can't go beyond the end of the string
			$length = min($strlen - $offset, $length);

			$x = (int) ($length / 65535);
			$y = (int) ($length % 65535);
			$regex .= '(';
			$regex .= ($x == 0) ? '' : ('(?:.{65535}){' . $x . '}');
			$regex .= '.{' . $y . '})';
		}
		// Find length from the right (negative length)
		else
		{
			$x = (int) (-$length / 65535);
			$y = (int) (-$length % 65535);
			$regex .= '(.*)';
			$regex .= ($x == 0) ? '' : ('(?:.{65535}){' . $x . '}');
			$regex .= '.{' . $y . '}';
		}

		preg_match('/' . $regex . '/us', $str, $matches);
		return $matches[1];
	}
    
    public static function formatPrice($unit_code, $price){
        $locale = self::$_locales[$unit_code];
        $currency = new Zend_Currency($locale);
		$currency_format = array(
            'value'     => $price,
            'display'   => Zend_Currency::NO_SYMBOL,
			'position'  => Zend_Currency::RIGHT
        );
        if(($price - floor($price) == 0)){
            $currency_format['precision'] = 0;
        }
        $currency->setFormat($currency_format);
		return $currency;
    }
    
    public static function getFormatCurrency($unit_code){
        $arrFormatCurrency = array(
            'thousand'  => ',',
            'decimal'   => '.'
        );
        
        $locale = self::$_locales[$unit_code];
        $formatCurrency = Zend_Locale_Data::getContent($locale, 'currencynumber');
        
        $regex = '/([,\.]*?)\#\#0([,\.]{1}?)00/';        
        $is_match = preg_match($regex, $formatCurrency, $matches);
        if($is_match){
            $arrFormatCurrency['thousand'] = $matches[1];
            $arrFormatCurrency['decimal'] = $matches[2];
        }
        
        if($unit_code == 'VND'){
            $arrFormatCurrency['thousand'] = '.';
            $arrFormatCurrency['decimal']  = ',';
        }
        return $arrFormatCurrency;
    }
}